/**
 * @Author       : Hejh(3010733382@qq.com)
 * @Version      : V1.0
 * @Date         : 2024-01-14 17:39:31
 * @Description  : 题目接口控制器
 */
const Mysequelize = require('@/models')
const R = require('@/models/Response')
const {
  Question,
  QuestionFav,
  ErrorQuestion,
  Paper
} = require('@/models/model')
const { ERROR_USER_CODE } = require('@/constants/errorCode')
const { generatId } = require('@/utils/idUtil')
const { delModel, sortModel } = require('@/utils/controllerCommon')

/**
 * 列表查询题目接口
 * @param {*} ctx
 * @returns
 */
module.exports.listQuestion = async (ctx) => {
  const orderCondition = [['sort']]
  const { page, pageSize, paperId } = ctx.query
  const start = (page - 1) * pageSize
  const whereCondition = {}
  if (paperId !== undefined) {
    whereCondition.paperId = paperId
  }
  const { rows, count } = await Question.findAndCountAll({
    where: whereCondition,
    offset: +start,
    limit: +pageSize,
    include: [
      {
        model: Paper
      }
    ],
    order: orderCondition,
    distinct: true
  })

  ctx.body = R.success({
    page,
    pageSize,
    total: count,
    pages: Math.ceil(count / pageSize),
    items: rows
  })
}

/**
 * @author: Hejh(3010733382@qq.com)
 * @description: 创建题目接口
 * @param {*} ctx
 */
module.exports.createQuestion = async (ctx) => {
  const {
    name,
    paperId,
    pic,
    answer,
    analysis,
    anaPics,
    options,
    type,
    score
  } = ctx.request.body
  const t = await Mysequelize.transaction()
  const nextId = generatId()
  const sort = await Question.max('sort')

  let createObj = {
    id: nextId,
    name,
    type: type || 1,
    paperId,
    answer,
    analysis,
    pic: pic || '',
    anaPics: anaPics || '',
    options: options || '',
    score: +score || 1,
    sort: sort + 1,
    createUser: ctx.user.id,
    updateUser: ctx.user.id
  }
  try {
    // 到这里可以进行题目的添加了,排序字段默认是最大值
    const question = await Question.create(createObj, {
      transaction: t
    })
    await t.commit()
    ctx.body = R.success()
  } catch (error) {
    await t.rollback()
    ctx.body = R.error(ERROR_USER_CODE.QUESTION_CREATE_ERROR)
  }
}

/**
 * @author: Hejh(3010733382@qq.com)
 * @description: 更新题目接口
 * @param {*} ctx
 */
module.exports.updateQuestion = async (ctx) => {
  const t = await Mysequelize.transaction()
  const {
    questionId,
    name,
    answer,
    pic,
    analysis,
    anaPics,
    options,
    type,
    score
  } = ctx.request.body
  const updateObj = {
    name
  }
  if (answer) {
    updateObj.answer = answer
  }
  if (pic) {
    updateObj.pic = pic
  }
  if (analysis) {
    updateObj.analysis = analysis
  }
  if (anaPics) {
    updateObj.anaPics = anaPics
  }
  if (options) {
    updateObj.options = options
  }
  if (type) {
    updateObj.type = type
  }
  if (score) {
    updateObj.score = score
  }

  try {
    // 进行题目信息的更新
    await Question.update(updateObj, {
      where: {
        id: BigInt(questionId)
      },
      transaction: t
    })
    await t.commit()
    ctx.body = R.success()
  } catch (e) {
    await t.rollback()
    ctx.body = R.error(ERROR_USER_CODE.QUESTION_UPDATE_ERROR)
  }
}

/**
 * @author: Hejh(3010733382@qq.com)
 * @description: 批量删除题目接口
 * @param {*} ctx
 */
module.exports.delQuestions = async (ctx) => {
  await delModel(
    Question,
    ERROR_USER_CODE.QUESTION_DEL_ERROR,
    'questionIds'
  )(ctx, [
    { model: QuestionFav, idName: 'questionId' },
    { model: ErrorQuestion, idName: 'questionId' }
  ])
}

/**
 * @author: Hejh(3010733382@qq.com)
 * @description: 题目排序接口
 * @param {*} ctx
 */
module.exports.sortQuestions = async (ctx) => {
  // 传递的题目ID顺序即为排序顺序，取出这些ID对应的sort，sort从小到大排序后，依次赋值
  await sortModel(
    Question,
    ERROR_USER_CODE.QUESTION_SORT_ERROR,
    'questionIds'
  )(ctx)
}
